// pages/user/dingdan.js
//index.js  
//获取应用实例  
var sliderWidth = 25;
var app = getApp();
var common = require("../../utils/common.js");
Page({  
  data: { 
    winWidth: 0,  
    winHeight: 0,  
    // tab切换  
    currentTab: 0,  
    isStatus:'pay',//10待付款，20待发货，30待收货 40、50已完成
    page:0,
    refundpage:0,
    itemData: {},
    obligationList: [],//待付款
    sendOutList: [],//待发货
    receivingList: [],//待收货
    finishedList: [],//已完成
    refundList: [],//退款
    // 修改
    tabs: ["待付款", "待发货", "待收货", "已完成", "退款/售后"],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    imageUrl: app.d.imageUrlFix,//图片地址
    isRefresh: 0,//下个页面传回的值
    //是否有数据
    isHaveData: {
      obIsHaveData: 0,//待付款是否有数据
      sendIsHaveData: 0,//待发货是否有数据
      receiveIsHaveData: 0,//待收货是否有数据
      finishIsHaveData: 0,//已完成是否有数
      refundIsHaveData: 0,//退款/售后是否有数据
    },
  },  
  onLoad: function(options) {
    var that = this;  
    this.initSystemInfo();
    this.setData({
      currentTab: parseInt(options.currentTab),
      isStatus:options.otype,
      activeIndex: parseInt(options.activeIndex),
      state:parseInt(options.state),
    });
    
    this.queryItemList();


    if(this.data.currentTab == 4){
      this.loadReturnOrderList();
    }else{
      // this.loadOrderList();
      // this.queryObligationList();
    }
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 4,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex,
        });
      },
    });
  },  

  /**
   * 点击导航栏
   */
  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
    this.queryItemList();
  },

  getOrderStatus:function(){
    return this.data.currentTab == 0 ? 1 : this.data.currentTab == 2 ?2 :this.data.currentTab == 3 ? 3:0;
  },

  /**
   * 从新刷新页面数据 
   */
  refreshThis: function(e){
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    //刷新界面
    that.queryItemList();
    if (that.data.isRefresh == 1) {
      wx.showToast({
        title: '操作成功',
        duration: 2000,
      })
      that.setData({
        isRefresh:0,
      });
    }
  },

  /**
   * 删除订单
   */
  delOrder: function(e){
    var that = this;
    var orderId = e.currentTarget.dataset.orderid;
    wx.showModal({
      title: '提示',
      content: '您确定要删除订单吗？',
      success: function(res){
        res.confirm && app.request("WxOrderListService", "modOrderStatus", {id: orderId, type: 'delete'}, function(data){
          wx.showToast({
            title: '删除成功！',
            duration: 2000
          })
          that.queryItemList();
        });
      }
    });
  },

//取消订单
removeOrder:function(e){
    var that = this;
    var orderId = e.currentTarget.dataset.orderid;
    wx.showModal({
      title: '提示',
      content: '你确定要取消订单吗？',
      success: function(res) {
        res.confirm && app.request("WxOrderListService", "modOrderStatus", { 
          id: orderId,type:'cancel'},function(data){
            wx.showToast({
              title: '操作成功！',
              duration: 2000
            });
            that.queryItemList();
        });
        // res.confirm && wx.request({
        //   url: app.d.ceshiUrl + '/Api/Order/orders_edit',
        //   method:'post',
        //   data: {
        //     id: orderId,
        //     type:'cancel',
        //   },
        //   header: {
        //     'Content-Type':  'application/x-www-form-urlencoded'
        //   },
        //   success: function (res) {
        //     //--init data
        //     var status = res.data.status;
        //     if(status == 1){
        //       wx.showToast({
        //         title: '操作成功！',
        //         duration: 2000
        //       });
        //       that.loadOrderList();
        //     }else{
        //       wx.showToast({
        //         title: res.data.err,
        //         duration: 2000
        //       });
        //     }
        //   },
        //   fail: function () {
        //     // fail
        //     wx.showToast({
        //       title: '网络异常！',
        //       duration: 2000
        //     });
        //   }
        // });

      }
    });
  },
/**
 * 选择支付方式
 */
payType: function(e){
  var that = this;
  var payType = e.currentTarget.dataset.paytype;
  var orderId = e.currentTarget.dataset.orderid;
  var order = e.currentTarget.dataset.order;
  if(payType == "wx"){
    that.payOrder(orderId, order);
  }
},

/**
 * 微信支付
 */
payOrder: function(orderId, order){
  var that = this;
  wx.showLoading({
    title: '数据加载中',
  });
  app.request("WxPaymentController", "getPayParam", {
    openid: app.globalData.userInfo['openid'],
    orderId: orderId,
    orderAmount: order.order_amount,
  },
    function (data) {
      wx.requestPayment({
        'timeStamp': data.timeStamp,
        'nonceStr': data.nonceStr,
        'package': data.package,
        'signType': data.signType,
        'paySign': data.paySign,
        'success': function (res) {
            app.request("WxPaymentController","orderQuery",{
              orderId: orderId
            },function(data){
              wx.hideLoading();
              wx.showToast({
                title: '操作成功',
                duration: 2000,
              });
              app.request("WxOrderListService", "modOrderStatus", {
                id: orderId,
                type: 'confirmPay',
                orderAmount: order.order_amount,
              }, function (data) {
                that.setData({
                  showModalStatus: false,
                })
                that.queryItemList();
              });
              
            },function(data){
              wx.hideLoading();
              wx.showToast({
                title: "数据更新失败！",
                duration: 2000,
              });
              that.setData({
                showModalStatus: false,
              })
              return false;
            }); 
        },
        'fail': function (res) {
          wx.hideLoading();
          wx.showToast({
            title: "支付失败",
            duration: 2000,
          });
          that.setData({
            showModalStatus: false,
          })  
        },
      })
    });
},
  //确认收货
recOrder:function(e){
    var that = this;
    var orderId = e.currentTarget.dataset.orderid;
    wx.showModal({
      title: '提示',
      content: '你确定已收到宝贝吗？',
      success: function(res) {
        res.confirm && app.request("WxOrderListService", "modOrderStatus", { id: orderId,type:'receive'},function(data){
          wx.showToast({
            title: '操作成功！',
            duration: 2000
          });
          that.queryItemList();
        });
    //     res.confirm && wx.request({
    //       url: app.d.ceshiUrl + '/Api/Order/orders_edit',
    //       method:'post',
    //       data: {
    //         id: orderId,
    //         type:'receive',
    //       },
    //       header: {
    //         'Content-Type':  'application/x-www-form-urlencoded'
    //       },
    //       success: function (res) {
    //         //--init data
    //         var status = res.data.status;
    //         if(status == 1){
    //           wx.showToast({
    //             title: '操作成功！',
    //             duration: 2000
    //           });
    //           that.loadOrderList();
    //         }else{
    //           wx.showToast({
    //             title: res.data.err,
    //             duration: 2000
    //           });
    //         }
    //       },
    //       fail: function () {
    //         // fail
    //         wx.showToast({
    //           title: '网络异常！',
    //           duration: 2000
    //         });
    //       }
    //     });

    //   }
    // });
      },
    })
  },

  /**
   * 查询列表
   */
  queryItemList:function() {
    if (this.data.activeIndex == 0) {
      this.queryObligationList();
    } else if (this.data.activeIndex == 1) {
      this.querySendOutList();
    } else if (this.data.activeIndex == 2) {
      this.queryReceivingList();
    } else if (this.data.activeIndex == 3) {
      this.queryFinishedList();
    } else if (this.data.activeIndex == 4) {
      this.queryRefundList();
    }
  },

  /**
   * 查询待付款列表
   */
  queryObligationList:function(){
    var that = this;
    var total = 0;
    wx.showLoading({
      title: '数据加载中',
    });
    app.request("WxOrderListService", "queryOrderList", 
      { userId: app.d.userId, orderStatus: 0, shippingStatus: 0, payStatus: 0}, function(data){
        wx.hideLoading();
        if(data.orderList !=null && data.orderList.length > 0){
          for (let i = 0; i < data.orderList.length; i++) {
            for (let j = 0; j < data.orderList[i].orderGoods.length; j++) {
              total += data.orderList[i].orderGoods[j].goods_number;
            }
            total = Math.round(total * 100) / 100;
            data.orderList[i]["totalAmount"] = total;
            total = 0;
          }
        }
        that.setData({
          obligationList: data.orderList,
        });
        if(that.data.obligationList.length > 0){
          that.setData({
            isHaveData: { obIsHaveData: 0 },
          });
        }else {
          that.setData({
            isHaveData: { obIsHaveData: 1 },
          });
        }
      }, function(data){
       
      }, function(data){
        wx.hideLoading();
      });
  },

  /**
   * 查询待发货列表
   */
  querySendOutList: function(){
    var that = this;
    var total = 0;
    wx.showLoading({
      title: '数据加载中',
    });
    app.request("WxOrderListService", "queryOrderList", {
      userId: app.d.userId, orderStatus: 0, shippingStatus: 0, payStatus: 2}, function(data){
        if (data.orderList != null && data.orderList.length > 0) {
          for (let i = 0; i < data.orderList.length; i++) {
            for (let j = 0; j < data.orderList[i].orderGoods.length; j++) {
              total += data.orderList[i].orderGoods[j].goods_number;
            }
            data.orderList[i]["totalAmount"] = total;
            total = 0;
          }
        }
        that.setData({
          sendOutList: data.orderList,
        });
        if (that.data.sendOutList.length > 0) {
          that.setData({
            isHaveData: { sendIsHaveData: 0 },
          });
        } else {
          that.setData({
            isHaveData: { sendIsHaveData: 1 },
          });
        }
      }, function (data) {

      }, function (data) {
        wx.hideLoading();
      });
  },

  /**
   * 查询待收获列表
   */
  queryReceivingList: function () {
    var that = this;
    var total = 0;
    wx.showLoading({
      title: '数据加载中',
    });
    app.request("WxOrderListService", "queryOrderList", {
      userId: app.d.userId, orderStatus: 0, shippingStatus: 1, payStatus: 2
    }, function (data) {
      if (data.orderList != null && data.orderList.length > 0) {
        for (let i = 0; i < data.orderList.length; i++) {
          for (let j = 0; j < data.orderList[i].orderGoods.length; j++) {
            total += data.orderList[i].orderGoods[j].goods_number;
          }
          data.orderList[i]["totalAmount"] = total;
          total = 0;
        }
      }
      that.setData({
        receivingList: data.orderList,
      });
      if (that.data.receivingList.length > 0) {
        that.setData({
          isHaveData: { receiveIsHaveData: 0 },
        });
      } else {
        that.setData({
          isHaveData: { receiveIsHaveData: 1 },
        });
      }
      }, function (data) {

      }, function (data) {
        wx.hideLoading();
      });
  },

  /**
   * 查询已完成列表
   */
  queryFinishedList: function () {
    var that = this;
    var total = 0;
    wx.showLoading({
      title: '数据加载中',
    });
    app.request("WxOrderListService", "queryOrderList", {
      userId: app.d.userId, orderStatus: 1, shippingStatus: 2, payStatus: 2
    }, function (data) {
      if (data.orderList != null && data.orderList.length > 0) {
        for (let i = 0; i < data.orderList.length; i++) {
          for (let j = 0; j < data.orderList[i].orderGoods.length; j++) {
            total += data.orderList[i].orderGoods[j].goods_number;
          }
          data.orderList[i]["totalAmount"] = total;
          total = 0;
        }
      }
      that.setData({
        finishedList: data.orderList,
      });
      if (that.data.finishedList.length > 0) {
        that.setData({
          isHaveData: { finishIsHaveData: 0 },
        });
      } else {
        that.setData({
          isHaveData: { finishIsHaveData: 1 },
        });
      }
      }, function (data) {

      }, function (data) {
        wx.hideLoading();
      });
  },

  /**
   * 查询退款列表
   */
  queryRefundList: function () {
    var that = this;
    var total = 0;
    
    wx.showLoading({
      title: '数据加载中',
    });
    app.request("WxOrderListService", "queryOrderList", {
      userId: app.d.userId, orderStatus: 4, shippingStatus: 4, payStatus: 2
    }, function (data) {
      if (data.orderList != null && data.orderList.length > 0) {
        for (let i = 0; i < data.orderList.length; i++) {
          for (let j = 0; j < data.orderList[i].orderGoods.length; j++) {
            total += data.orderList[i].orderGoods[j].goods_number;
          }
          data.orderList[i]["totalAmount"] = total;
          total = 0;
        }
      }
      that.setData({
        refundList: data.orderList,
      });
      if (that.data.refundList.length > 0) {
        that.setData({
          isHaveData: { refundIsHaveData: 0 },
        });
      } else {
        that.setData({
          isHaveData: { refundIsHaveData: 1 },
        });
      }
    }, function (data) {

    }, function (data) {
      wx.hideLoading();
    });
  },




  // loadOrderList: function(){
  //   var that = this;
    // wx.request({
    //   url: app.d.ceshiUrl + '/Api/Order/index',
    //   method:'post',
    //   data: {
    //     uid:app.d.userId,
    //     order_type:that.data.isStatus,
    //     page:that.data.page,
    //   },
    //   header: {
    //     'Content-Type':  'application/x-www-form-urlencoded'
    //   },
    //   success: function (res) {
    //     //--init data        
    //     var status = res.data.status;
    //     var list = res.data.ord;
    //     switch(that.data.currentTab){
    //       case 0:
    //         that.setData({
    //           orderList0: list,
    //         });
    //         break;
    //       case 1:
    //         that.setData({
    //           orderList1: list,
    //         });
    //         break;  
    //       case 2:
    //         that.setData({
    //           orderList2: list,
    //         });
    //         break;
    //       case 3:
    //         that.setData({
    //           orderList3: list,
    //         });
    //         break;
    //       case 4:
    //         that.setData({
    //           orderList4: list,
    //         });
    //         break;  
    //     }
    //   },
    //   fail: function () {
    //     // fail
    //     wx.showToast({
    //       title: '网络异常！',
    //       duration: 2000
    //     });
    //   }
    // });
  // },

loadReturnOrderList:function(){
    var that = this;
    wx.request({
      url: app.d.ceshiUrl + '/Api/Order/order_refund',
      method:'post',
      data: {
        uid:app.d.userId,
        page:that.data.refundpage,
      },
      header: {
        'Content-Type':  'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data        
        var data = res.data.ord;
        var status = res.data.status;
        if(status==1){
          that.setData({
            orderList4: that.data.orderList4.concat(data),
          });
        }else{
          wx.showToast({
            title: res.data.err,
            duration: 2000
          });
        }
      },
      fail: function () {
        // fail
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    });
  },
  
  // returnProduct:function(){
  // },
  initSystemInfo:function(){
    var that = this;  
  
    wx.getSystemInfo( {
      success: function( res ) {  
        that.setData( {  
          winWidth: res.windowWidth,  
          winHeight: res.windowHeight  
        });  
      }    
    });  
  },
  bindChange: function(e) {  
    var that = this;  
    that.setData( { currentTab: e.detail.current });  
  },  
  swichNav: function(e) {  
    var that = this;  
    if( that.data.currentTab === e.target.dataset.current ) {  
      return false;  
    } else { 
      var current = e.target.dataset.current;
      that.setData({
        currentTab: parseInt(current),
        isStatus: e.target.dataset.otype,
      });

      //没有数据就进行加载
      switch(that.data.currentTab){
          case 0:
            !that.data.obligationList.length && that.loadOrderList();
            break;
          case 1:
            !that.data.sendOutList.length && that.loadOrderList();
            break;  
          case 2:
           !that.data.receivingList.length && that.loadOrderList();
            break;
          case 3:
            !that.data.finishedList.length && that.loadOrderList();
            break;
          case 4:
            that.data.refundList.length = 0;
            that.loadReturnOrderList();
            break;
        }
    };
  },
  /**
   * 微信支付订单
   */
  // payOrderByWechat: function(event){
  //   var orderId = event.currentTarget.dataset.orderId;
  //   this.prePayWechatOrder(orderId);
  //   var successCallback = function(response){
  //     console.log(response);
  //   }
  //   common.doWechatPay("prepayId", successCallback);
  // },

  payOrderByWechat: function (e) {
    var order_id = e.currentTarget.dataset.orderId;
    var order_sn = e.currentTarget.dataset.ordersn;
    if(!order_sn){
      wx.showToast({
        title: "订单异常!",
        duration: 2000,
      });
      return false;
    }
    wx.request({
      url: app.d.ceshiUrl + '/Api/Wxpay/wxpay',
      data: {
        order_id: order_id,
        order_sn: order_sn,
        uid: app.d.userId,
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }, // 设置请求的 header
      success: function (res) {
        if (res.data.status == 1) {
          var order = res.data.arr;
          wx.requestPayment({
            timeStamp: order.timeStamp,
            nonceStr: order.nonceStr,
            package: order.package,
            signType: 'MD5',
            paySign: order.paySign,
            success: function (res) {
              wx.showToast({
                title: "支付成功!",
                duration: 2000,
              });
              setTimeout(function () {
                wx.navigateTo({
                  url: '../user/dingdan?currentTab=1&otype=deliver',
                });
              }, 3000);
            },
            fail: function (res) {
              wx.showToast({
                title: res,
                duration: 3000
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.err,
            duration: 2000
          });
        }
      },
      fail: function (e) {
        // fail
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    })
  },

  // 弹窗
  setModalStatus: function (e) {
    // wx.navigateTo({
    //   url: '../order/pay?order=' + JSON.stringify(order),
    // })
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })

    this.animation = animation
    animation.translateY(300).step();

    this.setData({
      animationData: animation.export()
    })

    if (e.currentTarget.dataset.status == 1) {

      this.setData(
        {
          showModalStatus: true
        }
      );
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (e.currentTarget.dataset.status == 0) {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 200);
    var order = e.currentTarget.dataset.order;
    this.setData({
      itemData: order
    })

  },

  /**
   * 调用服务器微信统一下单接口创建一笔微信预订单
   */
//   prePayWechatOrder: function(orderId){
//     var uri = "/ztb/userZBT/GetWxOrder";
//     var method = "post";
//     var dataMap = {
//       SessionId: app.globalData.userInfo.sessionId,
//       OrderNo: orderId
//     }
//     console.log(dataMap);
//     var successCallback = function (response) {
//       console.log(response);
//     };
//     common.sentHttpRequestToServer(uri, dataMap, method, successCallback);
//   }
})